
var global = null;
// 购物车列表的前端js操作
function loadCartList () {
  $.ajax({
    url: "http://127.0.0.1:3000/cart/findCart",
    type: "post",
    data: {},
    success: function (res) {
      console.log(res)
      // 根据商店id 把一维数组 整理为对象包裹数组
      var obj = {
      }
      $.each(res, function (index, ele) {
        if (obj[ele.storeId]) {
          obj[ele.storeId].push(ele)
        } else {
          obj[ele.storeId] = [];
          obj[ele.storeId].push(ele)
        }
      })
      console.log(obj)
      // -------------------------------------------------
      // 渲染购物车
      var str = ""
      for (var x in obj) {

        // 生成商店内的商品元素
        var prostr = ""
        $.each(obj[x], function (index, ele) {
          prostr += `
            <div class="shop_one" pid="${ele._id}">
                <div class="product">
                  <input type="checkbox"  sid="${ele.storeId}"  ${ele.is_check == "1" ? 'checked' : ''} class="cks" > 
                  <img src="${ele.image}" alt="">
                  <span class="pname">${ele.goods_name}</span>
                </div>
                <div class="price">
                  <del>${ele.oldprice}</del>
                  <p>${ele.price}</p>
                </div>
                <div class="num">
                  <button onclick="plusAndMin('${ele._id}','${ele.num}','min')">-</button>
                  <input type="text" value="${ele.num}">
                  <button onclick="plusAndMin('${ele._id}','${ele.num}','plus')">+</button>
                </div>
                <div>
                  ${(Number(ele.price) * Number(ele.num)).toFixed(2)}
                </div>
                <div>
                  <a class="del"   pid="${ele._id}" href="#">删除</a>
                </div>
              </div>
            `
        })
        str += ` <div class="shop">
            <div class="shop_title">
              <input type="checkbox"  ${obj[x][0].isall == "1" ? "checked" : ""}   class="storeall"  sid="${obj[x][0].storeId}" ><span>${obj[x][0].stroename}</span>
            </div> 
            <div class="shop_list">
                  ${prostr}
            </div>
          </div>`
      }
      $(".cart_info").html(str)
      checkAll();//判断购物车是否该全选
      total(res)//计算总价函数
    }
  })
}
loadCartList()
// 删除方法
$(".cart_info").on("click", ".del", function () {
  var _id = $(this).attr("pid");//获取绑定的自定义属性的id
  $.ajax({
    url: "http://127.0.0.1:3000/cart/del",
    type: "post",
    data: {
      _id: _id
    },
    success: function (res) {
      if (res.success) {
        alert("删除成功")
        loadCartList()
      }
    }
  })
})
// 单选
$(".cart_info").on("click", ".cks", function () {
  // 选中
  var _id = $(this).parent().parent().attr("pid");//_id 
  console.log($(this).prop("checked"))
  var is_check = $(this).prop("checked") ? "1" : "0"
  var sid = $(this).attr("sid");
  console.log(is_check)
  $.ajax({
    url: "http://127.0.0.1:3000/cart/ischeck",
    type: "post",
    data: {
      _id: _id,
      is_check: is_check,
      storeId: sid
    },
    success: function (res) {

      loadCartList()
    }
  })
})
// 商店全选--------------------------
$(".cart_info").on("click", ".storeall", function () {

  var sid = $(this).attr("sid")//商店id
  var is_check = $(this).prop("checked") ? "1" : "0"
  console.log(is_check)
  $.ajax({
    url: "http://127.0.0.1:3000/cart/storeAll",
    type: "post",
    data: {
      storeId: sid,
      is_check: is_check
    },
    success: function () {
      loadCartList()
    }
  })
})

// 全选
$("#checkAll").click(function () {
  var all = $(this).prop("checked") ? "1" : "0"
  $.ajax({
    url: "http://127.0.0.1:3000/cart/allcheck",
    type: "post",
    data: {
      all: all
    },
    success: function () {
      loadCartList()
    }
  })
})
// 判断购物车全选按钮
function checkAll () {
  var flag = true;

  $.each($(".cks"), function (index, ele) {
    console.log($(ele).prop("checked"))
    if (!$(ele).prop("checked")) {
      flag = false;
    }
  })
  $("#checkAll").prop("checked", flag)
}
// 批量删除
$("#delCheck").click(function () {
  var ids = [];
  $.each($(".cks"), function (index, ele) {
    if (ele.checked) {
      ids.push(ele.parentNode.parentNode.getAttribute("pid"));
    }
  })
  console.log(ids)
  $.each(ids, function (index, ele) {
    $.ajax({
      url: "http://127.0.0.1:3000/cart/del",
      type: "post",
      data: {
        _id: ele
      },
      success: function () {
        loadCartList()
      }
    })
  })
})
// 加和减 更新购物数量
function plusAndMin (_id, num, status) {
  console.log()
  if (status == "plus") {
    num++
  } else {
    num--
    if (num <= 1) {
      num = 1;
    }
  }
  $.ajax({
    url: "http://127.0.0.1:3000/cart/updateNum",
    type: "post",
    data: {
      _id: _id,
      num: num
    },
    success: function (res) {
      loadCartList()
    }
  })
}
// 计算总价的函数
function total (arr) {
  var count = 0;
  var mynum = 0;
  for (var i = 0; i < arr.length; i++) {
    if (arr[i].is_check == "1") {
      count += Number(arr[i].num) * Number(arr[i].price);
      mynum += Number(arr[i].num);
    }
  }
  $(".total").html(count)
  $(".total_wrap p").eq(0).html("已选中：" + mynum + "件商品")
}